﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BYRBBS.Model;
using BYRBBS.Util;
using BYRBBS.MyDebug;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;

namespace BYRForum
{
    public partial class MailPage : PhoneApplicationPage
    {
        string index;
        string box;
        public MailPage()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            PageTitle.Text=this.NavigationContext.QueryString["BoxName"];
            index=this.NavigationContext.QueryString["index"];
            box=this.NavigationContext.QueryString["box"];

            String myRequestUrl = ByrApi.apiUrl + "/mail/" + box+"/"+index + ByrApi.Encode + ByrApi.appkey;
            RequestState state = new RequestState();
            HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_Mail_Callback);//发送请求
            base.OnNavigatedTo(e);
        }
        private void HttpWebRequset_Mail_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                DebugInfo.writeXml(result);
                string ErrorInfo;
                Mail mail = ParseUtil.ParseXml<Mail>(result, out ErrorInfo);
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    SendId.Text = mail.User.Id;
                    Title.Text = mail.Title;

                    DateTime dtStart = new DateTime(1970, 1, 1);//这是发帖时间格式转换
                    long lTime = long.Parse(mail.Post_time + "0000000");
                    TimeSpan toNow = new TimeSpan(lTime);
                    DateTime dtResult = dtStart.Add(toNow);

                    PostTime.Text = dtResult.ToString("yyyy-MM-dd HH:mm:ss");
                    Content.Text = mail.Content;
                }));
            }
            catch
            {
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() =>
                {
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }

        private void Delete_Clicked(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除信件？", "删除", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            String myRequestUrl = ByrApi.apiUrl + "/mail/" + box + "/delete/" + index + ByrApi.Encode + ByrApi.appkey;
            HttpUtil.HttpPost(myRequestUrl, HttpWebRequset_Delete_Callback);//发送请求
        }
        private void HttpWebRequset_Delete_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                try
                {
                    HttpWebRequest hwrq = (HttpWebRequest)asynchronousResult.AsyncState;
                    hwrq.BeginGetResponse(PostResponse_Callback, hwrq);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("POST STRING FAILED:" + e.Message);
                }
            }
            catch
            {
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() =>
                {
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }
        private void PostResponse_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                XDocument doc = XDocument.Parse(result);
                DebugInfo.writeXml(result);
                foreach (XElement item in doc.Descendants("error").Nodes())
                {
                    if (item.Name == "msg")
                    {
                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                MessageBox.Show("删除信件失败：" + item.Value);
                            }
                            );


                        return;
                    }
                }
                this.Dispatcher.BeginInvoke(
                    () =>
                    {
                        MessageBox.Show("删除信件成功！");
                        this.NavigationService.GoBack();
                    }
                    );
            }
            catch { }



        }
        private void Reply_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/EditMailPage.xaml?from=reply&sendId="+SendId.Text+"&title=RE:"+Title.Text, UriKind.Relative));
        }

        private void Forward_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BYRForum;component/EditMailPage.xaml?from=forward", UriKind.Relative));
        }
    }
}